package com.funcourse.demo.api.restful.security;

import com.funcourse.demo.api.ApiSystemConstants;
import com.funcourse.demo.model.User;
import com.funcourse.demo.model.repo.UserRepo;
import java.io.IOException;
import java.util.Date;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class TokenAuthFilter implements Filter {

  @Autowired
  private UserRepo userRepo;

  @Override
  public void destroy() {

  }

  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletResponse httpServletResponse = (HttpServletResponse) response;
    httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");

    httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");

    httpServletResponse.setHeader("Access-Control-Allow-Methods", "*");

    httpServletResponse.setHeader("Access-Control-Allow-Headers", "Content-Type,Access-Token,Authorization");

    httpServletResponse.setHeader("Access-Control-Expose-Headers", "*");
    if("OPTIONS".equalsIgnoreCase(httpRequest.getMethod())){
      httpServletResponse.setStatus(200);
      return;
    }
    String token = httpRequest.getHeader("Authorization");
    log.info("token {} from {} is accessing {}", token, httpRequest.getRemoteAddr(),
        httpRequest.getRequestURL());
    User auth;
    if(null == token ){
      auth = null;
    }else{
      auth = userRepo.findByToken(token);
    }
    if (null != auth) {
      request.setAttribute(ApiSystemConstants.SERVLET_ATTR_AUTH, auth);
      chain.doFilter(request, response);
    } else {
      HttpServletResponse httpResponse = (HttpServletResponse) response;
      httpResponse.sendError(403);
    }

  }

  @Override
  public void init(FilterConfig arg0) throws ServletException {

  }

}
